package cn.lingyangwl.framework.tool.core.exception;

import cn.hutool.core.util.StrUtil;
import lombok.Getter;
import lombok.Setter;
import org.springframework.http.HttpStatus;

/**
 * 基础异常
 *
 * @author shenguangyang
 */
@Getter
@Setter
public class BaseException extends RuntimeException {
    private static final long serialVersionUID = 1L;

    /**
     * 错误码
     */
    protected Integer code;

    /**
     * 错误消息
     */
    protected String message;

    protected Object data;

    private HttpStatus status;

    /**
     * 错误是否展示给http调用方 <br/>
     * 1. true: 会被全局异常拦截器拦截并返回错误信息 </br>
     * 2. false: 只打印错误日期, 且会返回正确响应(springboot全局拦截器中不会做任何处理)
     */
    protected boolean isShow = true;

    /**
     * Constructs a new runtime exception with {@code null} as its
     * detail message.  The cause is not initialized, and may subsequently be
     * initialized by a call to {@link #initCause}.
     */
    public BaseException() {
    }

    public BaseException(boolean isShow, Integer code, String message) {
        this.isShow = isShow;
        this.code = code;
        this.message = message;
    }

    public BaseException(Integer code, String message) {
        this.code = code;
        this.message = message;
    }

    /**
     * 格式化文本, {} 表示占位符<br>
     * 此方法只是简单将占位符 {} 按照顺序替换为参数<br>
     *
     * @param code        代码
     * @param msgTemplate 消息模板, eg: \\hello {}, age \\{}
     * @param msgValues   消息模板值: eg: java, 20
     */
    public BaseException(Integer code, String msgTemplate, Object... msgValues) {
        this.code = code;
        this.message = StrUtil.format(msgTemplate, msgValues);
    }

    public BaseException(boolean isShow, Integer code, String msgTemplate, Object... msgValues) {
        this.isShow = isShow;
        this.code = code;
        this.message = StrUtil.format(msgTemplate, msgValues);
    }

    /**
     * 格式化文本, {} 表示占位符<br>
     * 此方法只是简单将占位符 {} 按照顺序替换为参数<br>
     *
     * @param msgTemplate 消息模板, eg: \\hello {}, age \\{}
     * @param msgValues   消息模板值: eg: java, 20
     */
    public BaseException(String msgTemplate, Object... msgValues) {
        this.message = StrUtil.format(msgTemplate, msgValues);
    }

    public BaseException(boolean isShow, String msgTemplate, Object... msgValues) {
        this.isShow = isShow;
        this.message = StrUtil.format(msgTemplate, msgValues);
    }

    public BaseException(String message) {
        this.message = message;
    }

    public BaseException(boolean isShow, String message) {
        this.isShow = isShow;
        this.message = message;
    }

    public BaseException(BaseError baseError) {
        this.message = baseError.getMessage();
        this.status = baseError.getStatus();
        this.code = baseError.getCode();
    }

    public BaseException data(Object data) {
        this.data = data;
        return this;
    }
}
